Skip to main content

Docker Compose Networking

  • Source
  • By default Compose sets up a single network for your app.
    • Each container for a service joins the default network and is both reachable by other containers on that network, and discover-able by them at a host-name identical to the container name.
  • For example, suppose your app is in a directory called myapp, and your docker-compose.yml looks like this:
version: "3.9"
services:
web:
build: .
ports:
- "8000:8000"
db:
image: postgres
ports:
- "8001:5432"
  • When you run docker compose up, the following happens:
    • A network called myapp_default is created.
    • A container is created using web’s configuration. It joins the network myapp_default under the name web.
    • A container is created using db’s configuration. It joins the network myapp_default under the name db.

Each container can now look up the host-name web or db and get back the appropriate container’s IP address. For example, web’s application code could connect to the URL postgres://db:5432 and start using the Postgres database.

HOST_PORT Vs CONTAINER_PORT

  • For db, the HOST_PORT is 8001 and the container port is 5432 (postgres default).
    • Outside applications use HOST_PORT and inside(inside container) applications use CONTAINER_PORT
  • Networked service-to-service communication uses the CONTAINER_PORT. When HOST_PORT is defined, the service is accessible outside the swarm as well.
  • Within the web container, your connection string to db would look like postgres://db:5432, and from the host machine, the connection string would look like postgres://{DOCKER_IP}:8001.
  • Links allow you to define extra aliases by which a service is reachable from another service.
  • They are not required to enable services to communicate - by default, any service can reach any other service at that service’s name.
  • In the following example, db is reachable from web at the hostnames both db and database.
version: "3.9"
services:
web:
build: .
links:
- "db:database"
db:
image: postgres

Specify Custom Networks

  • Instead of just using the default app network, you can specify your own networks with the top-level networks key.
  • This lets you create more complex topologies and specify custom network drivers and options.
  • Each service can specify what networks to connect to with the service-level networks key, which is a list of names referencing entries under the top-level networks key.
version: "3.9"

services:
proxy:
build: ./proxy
networks: # specify which custom network to connect to at service level networks key
- frontend
app:
build: ./app
networks:
- frontend
- backend
db:
image: postgres
networks:
- backend

networks: # define your custom networks at top level networks key
frontend:
backend:
  • Based on the above custom network definition
    • The proxy service is isolated from the db service, because they do not share a network in common - only app can talk to both.

More